<template>
	<DialogBox v-model:visible="drawerVisible" :title="`${drawerProps.title}${$t('role_form.dialog_title.role')}`" width="750px">
		<el-form
			v-if="drawerVisible"
			ref="ruleFormRef"
			label-width="100px"
			label-suffix=" :"
			:rules="rules"
			:disabled="drawerProps.isView"
			:model="drawerProps.rowData"
			:hide-required-asterisk="drawerProps.isView"
		>
			<el-form-item :label="$t('role_form.form_label.rolename')" prop="roleName">
				<el-input
					v-model="drawerProps.rowData!.roleName"
					:placeholder="$t('role_form.placeholder.rolename')"
					clearable
				></el-input>
			</el-form-item>
			<el-form-item :label="$t('role_form.form_label.remark')" prop="remark">
				<el-input
					v-model="drawerProps.rowData!.remark"
					type="textarea"
					:placeholder="$t('role_form.placeholder.remark')"
					clearable
				></el-input> </el-form-item
			><el-form-item :label="$t('role_form.form_label.relative')" class="relative">
				<div class="absolute" style="top: 30px; left: -85px">
					<el-link type="primary" @click="changeSelectMenu('all')">{{ $t("role_form.link.all") }}</el-link>
					<span class="p-1">|</span>
					<el-link type="primary" @click="changeSelectMenu('clean')">{{ $t("role_form.link.clean") }}</el-link>
				</div>
				<el-tabs v-model="state.type" :class="`w-full ${state.appletList.length > 1 ? '' : 'collapsed'}`">
					<el-tab-pane
						v-for="item in state.appletList"
						:key="item.menuSystemId || item.id"
						:label="item.name"
						:name="item.menuSystemId || item.id"
					>
						<TreeFilter
							:ref="`menuTreeEl-${item.menuSystemId || item.id}`"
							v-if="drawerVisible"
							class="h-96 w-full"
							:params="{ systemid: item.menuSystemId || item.id }"
							multiple
							:requestApi="getAllMenuList"
							id="id"
							label="menuName"
							:dataCallback="dataCallback"
							:defaultValue="checkedList"
							:isCheckStrictly="state.menusStrictly[item.menuSystemId || item.id]"
							@tree-ref-mounted="state.menusStrictly[item.menuSystemId || item.id] = false"
						/>
					</el-tab-pane>
				</el-tabs>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="drawerVisible = false">{{ $t("role_form.footer.cancel") }}</el-button>
			<el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">{{
				$t("role_form.footer.confirm")
			}}</el-button>
		</template>
	</DialogBox>
</template>

<script setup lang="ts" name="UserDrawer">
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import { Applet } from "@/api/interface/iot";
import { getUserAppletList } from "@/api/modules/applet/userApplet";
import { getRoleMenuList } from "@/api/modules/role";
import { getAllMenuList } from "@/api/modules/user";
import DialogBox from "@/components/DialogBox";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { showTips } from "@/utils/util";
import { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { RoleModel } from "../interface";
import { TreeNodeData } from "element-plus/es/components/tree/src/tree.type";
import { SYSTEM_ID } from "@/config/config";

const instance = getCurrentInstance();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const state = reactive({
	menus: {} as { [key: string]: any },
	menusStrictly: {} as { [key: string]: boolean },
	type: "",
	appletList: [] as Applet.ResUserApplet[]
});
const rules = reactive({
	roleName: [{ required: true, message: proxy?.$t("role_form.rules.rolename") }]
});
interface DrawerProps {
	title: string;
	isView: boolean;
	rowData?: RoleModel;
	api?: (params: any) => Promise<any>;
	getTableList?: () => Promise<any>;
}

// drawer框状态
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	rowData: { id: "" },
	isView: false,
	title: ""
});
function changeSelectMenu(type: "all" | "clean") {
	let dataList: TreeNodeData[] = [];
	function getIdList(list: any[]) {
		if (!list) {
			return;
		}
		list.forEach((item: any) => {
			dataList.push(item);
			if (item.children && item.children.length) {
				getIdList(item.children);
			}
		});
	}
	let el: any = instance?.proxy?.$refs[`menuTreeEl-${state.type}`];
	if (!el) {
		return;
	}
	getIdList(el.treeData);
	el!.handleAllChecked(dataList, type == "all");
}

onMounted(() => {
	getAppletList();
});
const getAppletList = async () => {
	//默认是三三菜单管理
	state.type = SYSTEM_ID;

	// state.appletList = [{ id: SYSTEM_ID, key: SYSTEM_ID, name: "三三物联" }];
	if (state.type == "sansan") {
		let { result } = await getUserAppletList({ pageIndex: 1, pageSize: 99999 });
		state.appletList = result.records;
		// state.appletList = state.appletList.concat(result.records || []);
	}
};
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps): Promise<void> => {
	drawerProps.value = params;
	await getCheckedMenuList();
	drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			//获取角色所有菜单
			let allMenuIds: string[] = [];
			state.appletList.forEach(item => {
				let el: any = instance?.proxy?.$refs[`menuTreeEl-${item.menuSystemId || item.id}`];
				if (!el) {
					return;
				}
				let keys1 = el[0].getCheckedKeys();
				let keys2 = el[0].getHalfCheckedKeys();
				allMenuIds = allMenuIds.concat(keys1, keys2);
			});
			drawerProps.value.rowData!.menuIds = allMenuIds.join(",");

			//提交数据
			let { code, message } = await drawerProps.value.api!(drawerProps.value.rowData);
			let ok = showTips(
				code,
				drawerProps.value.rowData?.id ? proxy?.$t("role_form.tips.mod") : proxy?.$t("role_form.tips.add"),
				message
			);
			if (ok) {
				drawerProps.value.getTableList!();
				drawerVisible.value = false;
			}
		} catch (error) {
			console.log(error);
		}
	});
};
// dataCallback 是对于返回的表格数据做处理，
const dataCallback = (data: any) => {
	return data.records.children;
};
//获取角色菜单权限
const checkedList = ref<any>([]);
const getCheckedMenuList = async () => {
	//设置每组菜单级联状态
	if (drawerProps.value.rowData) {
		let { result } = await getRoleMenuList(drawerProps.value.rowData.id);
		checkedList.value = result;
	}
	//设置每组菜单级联状态
	state.appletList.forEach(item => {
		state.menusStrictly[item.menuSystemId || item.id] = true;
	});
};
defineExpose({
	acceptParams
});
</script>
<style lang="scss">
.el-tabs.collapsed {
	.el-tabs__header {
		display: none;
	}
}
</style>
<style lang="scss" scoped>
:deep(.el-tree) {
	.el-tree-node__content {
		height: 20px !important;
	}
}
:deep(.filter) {
	padding: 0;
	margin-right: 0;
}
:deep(.el-form-item:last-child) {
	margin-bottom: 0;
}
</style>
